package xju.rjxy.shop.service.impl;

import xju.rjxy.shop.common.utils.PasswordUtil;
import xju.rjxy.shop.constant.BaseConstant;
import xju.rjxy.shop.mapper.UserMapper;
import xju.rjxy.shop.mapper.impl.UserMapperImpl;
import xju.rjxy.shop.model.domain.User;
import xju.rjxy.shop.model.dto.LoginDTO;
import xju.rjxy.shop.model.dto.RegisterDTO;
import xju.rjxy.shop.model.dto.UserUpdateDTO;
import xju.rjxy.shop.model.vo.UserVO;
import xju.rjxy.shop.model.vo.UserWithGamesVO;
import xju.rjxy.shop.model.vo.UserGameVO;
import xju.rjxy.shop.service.IUserService;
import xju.rjxy.shop.service.IUserGameService;
import xju.rjxy.shop.service.impl.UserGameServiceImpl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 用户服务接口实现类
 */
public class UserServiceImpl implements IUserService {
    private final UserMapper userMapper = new UserMapperImpl();
    private final IUserGameService userGameService = new UserGameServiceImpl();

    /**
     * 获取用户列表
     */
    @Override
    public List<UserVO> getUserList() {
        List<UserVO> userList = userMapper.selectUserList();
        if (userList != null && userList.size() > 0) {
            userList.forEach(user -> {
                // 处理状态文本值
                user.setFlagValue(getFlagValue(user.getFlag()));
            });
        }
        return userList;
    }
    
    /**
     * 用户登录
     */
    @Override
    public User login(LoginDTO loginDTO) {
        // System.out.println(loginDTO.getUsername());
        // System.out.println(loginDTO.getPassword());
        // System.out.println(loginDTO.getUsername());
        if (loginDTO == null || loginDTO.getUsername() == null || loginDTO.getPassword() == null) {

            throw new RuntimeException("用户名和密码不能为空");
        }
        
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // System.out.println(loginDTO.getPassword());

        // 验证密码
        if (!PasswordUtil.verifyPassword(loginDTO.getPassword(), user.getPassword())) {
            // System.out.println(user.getPassword());
            throw new RuntimeException("密码错误");
        }
        
        // 检查用户状态
        if (user.getFlag() != 2) {
            throw new RuntimeException("用户状态异常");
        }
        
        return user;
    }
    
    /**
     * 用户注册
     */
    @Override
    public User register(RegisterDTO registerDTO) {
        System.out.println(registerDTO.getUsername());
        System.out.println(registerDTO.getPhoneNumber());
        System.out.println(registerDTO.getPassword());
        if (registerDTO == null || registerDTO.getUsername() == null ||
            registerDTO.getPassword() == null || registerDTO.getPhoneNumber() == null) {
            throw new RuntimeException("注册信息不完整");
        }
        
        // 验证手机号格式
        if (!isValidPhoneNumber(registerDTO.getPhoneNumber())) {
            throw new RuntimeException("手机号格式不正确");
        }
        
        // 检查手机号是否已注册
        User existingUserByPhone = userMapper.selectByPhoneNumber(registerDTO.getPhoneNumber());
        if (existingUserByPhone != null) {
            throw new RuntimeException("手机号已被注册");
        }
        
        // 检查用户名是否已存在
        User existingUserByUsername = userMapper.selectByUsername(registerDTO.getUsername());
        if (existingUserByUsername != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 验证用户名格式
        if (!isValidUsername(registerDTO.getUsername())) {
            throw new RuntimeException("用户名格式不正确");
        }
        
        // 创建新用户
        User newUser = new User();
        newUser.setUsername(registerDTO.getUsername());
        newUser.setPhoneNumber(registerDTO.getPhoneNumber());
        newUser.setPassword(PasswordUtil.encryptMD5(registerDTO.getPassword()));
        newUser.setCreateTime(LocalDateTime.now());
        newUser.setFlag(2); // 有效状态
        newUser.setDeleted(false);
        newUser.setAccountBalance(0.0);
        newUser.setAccountPoints(0);
        newUser.setActivateCode(UUID.randomUUID().toString());
        
        // 插入用户
        int result = userMapper.insertUser(newUser);
        if (result <= 0) {
            throw new RuntimeException("注册失败");
        }
        
        return newUser;
    }
    
    /**
     * 根据ID获取用户信息
     */
    @Override
    public User getUserById(Integer id) {
        if (id == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        return userMapper.selectById(id);
    }
    
    /**
     * 更新用户信息
     */
    @Override
    public boolean updateUserInfo(User user) {
        if (user == null || user.getId() == null) {
            throw new RuntimeException("用户信息不完整");
        }
        
        int result = userMapper.updateUser(user);
        return result > 0;
    }
    
    @Override
    public boolean updateUserInfoByDTO(UserUpdateDTO userUpdateDTO) {
        System.out.println("=== UserService.updateUserInfoByDTO 调试信息 ===");
        System.out.println("输入参数: " + userUpdateDTO);
        
        if (userUpdateDTO == null) {
            System.out.println("错误: userUpdateDTO为null");
            return false;
        }
        
        if (userUpdateDTO.getId() == null) {
            System.out.println("错误: 用户ID为null");
            return false;
        }
        
        System.out.println("参数验证通过，用户ID: " + userUpdateDTO.getId());
        
        // 查询用户
        System.out.println("--- 查询用户信息 ---");
        User user = userMapper.selectById(userUpdateDTO.getId());
        if (user == null) {
            System.out.println("错误: 用户不存在，ID: " + userUpdateDTO.getId());
            return false;
        }
        System.out.println("查询到用户: " + user.getUsername());
        
        // 更新用户信息
        System.out.println("--- 更新用户信息 ---");
        boolean hasUpdate = false;
        
        if (userUpdateDTO.getUsername() != null) {
            System.out.println("更新用户名: " + user.getUsername() + " -> " + userUpdateDTO.getUsername());
            user.setUsername(userUpdateDTO.getUsername());
            hasUpdate = true;
        }
        if (userUpdateDTO.getEmail() != null) {
            System.out.println("更新邮箱: " + user.getEmail() + " -> " + userUpdateDTO.getEmail());
            user.setEmail(userUpdateDTO.getEmail());
            hasUpdate = true;
        }
        if (userUpdateDTO.getGender() != null) {
            System.out.println("更新性别: " + user.getGender() + " -> " + userUpdateDTO.getGender());
            user.setGender(userUpdateDTO.getGender());
            hasUpdate = true;
        }
        if (userUpdateDTO.getAvatar() != null) {
            System.out.println("更新头像: " + user.getAvatar() + " -> " + userUpdateDTO.getAvatar());
            user.setAvatar(userUpdateDTO.getAvatar());
            hasUpdate = true;
        }
        
        if (!hasUpdate) {
            System.out.println("警告: 没有需要更新的字段");
            return true; // 没有更新也算成功
        }
        
        // 调用Mapper更新
        System.out.println("--- 调用Mapper更新 ---");
        int result = userMapper.updateUser(user);
        System.out.println("Mapper更新结果: " + result);
        
        boolean success = result > 0;
        System.out.println("更新操作结果: " + success);
        return success;
    }

    @Override
    public boolean resetPassword(String phoneNumber, String username, String newPassword) {
        if (phoneNumber == null || username == null || newPassword == null) {
            return false;
        }
        // 用手机号查找用户
        User user = userMapper.selectByPhoneNumber(phoneNumber);
        if (user == null) {
            return false;
        }
        // 对比用户名
        if (!username.equals(user.getUsername())) {
            return false;
        }
        // 密码加密存储
        String encryptedPwd = PasswordUtil.encryptMD5(newPassword);
        user.setPassword(encryptedPwd);
        // 更新用户
        return userMapper.updateUser(user) > 0;
    }

    @Override
    public boolean uploadAvatar(Integer userId, String avatarUrl) {
        if (userId == null || avatarUrl == null) {
            return false;
        }
        
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }
        
        user.setAvatar(avatarUrl);
        return userMapper.updateUser(user) > 0;
    }
    
    @Override
    public boolean rechargeBalance(Integer userId, Double amount) {
        if (userId == null || amount == null || amount <= 0) {
            return false;
        }
        
        User user = userMapper.selectById(userId);
        // System.out.println(user.getPhoneNumber());
        // System.out.println(user.getUsername());
        if (user == null) {
            return false;
        }
        
        // 更新余额
        Double currentBalance = user.getAccountBalance() != null ? user.getAccountBalance() : 0.0;
        user.setAccountBalance(currentBalance + amount);
        
        return userMapper.updateUser(user) > 0;
    }

    private String getFlagValue(Integer flag) {
        if (flag == null) {
            return BaseConstant.EMPTY;
        }

        // hard code
        switch (flag) {
            case 1:
                return BaseConstant.FLAG_01;
            case 2:
                return BaseConstant.FLAG_02;
            case 3:
                return BaseConstant.FLAG_03;
            case 4:
                return BaseConstant.FLAG_04;
            default:
                return BaseConstant.EMPTY;
        }
    }
    
    /**
     * 验证手机号格式
     */
    private boolean isValidPhoneNumber(String phoneNumber) {
        return phoneNumber != null && phoneNumber.matches("^1[3-9]\\d{9}$");
    }
    
    /**
     * 验证用户名格式
     */
    private boolean isValidUsername(String username) {
        return username != null && username.length() >= 3 && username.length() <= 20 
               && username.matches("^[a-zA-Z0-9_]+$");
    }

    @Override
    public Integer findUserIdByUsernameOrPhone(String keyword) {
        User user = userMapper.selectByUsernameOrPhone(keyword);
        if (user == null) {
            return null;
        }
        return user.getId();
    }

    @Override
    public UserVO findUserVOByUsernameOrPhone(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) return null;
        User user = userMapper.selectByUsernameOrPhone(keyword);
        if (user == null) return null;
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setPhoneNumber(user.getPhoneNumber());
        userVO.setEmail(user.getEmail());
        userVO.setGender(user.getGender());
        userVO.setAvatar(user.getAvatar());
        userVO.setAccountBalance(user.getAccountBalance());
        userVO.setAccountPoints(user.getAccountPoints());
        userVO.setCreateTime(user.getCreateTime());
        userVO.setFlag(user.getFlag());
        userVO.setActivateCode(user.getActivateCode());
        userVO.setDeleted(user.getDeleted());
        // 不返回密码
        userVO.setPassword(null);
        return userVO;
    }
    
    @Override
    public UserWithGamesVO findUserWithGamesByUsernameOrPhone(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) return null;
        
        // 获取用户基本信息
        UserVO userVO = findUserVOByUsernameOrPhone(keyword);
        if (userVO == null) return null;
        
        // 创建包含游戏库的用户信息对象
        UserWithGamesVO userWithGamesVO = new UserWithGamesVO();
        userWithGamesVO.setUserInfo(userVO);
        
        // 获取用户游戏库列表
        List<UserGameVO> gameList = userGameService.getUserGameListByUserId(userVO.getId());
        userWithGamesVO.setGameList(gameList);
        
        // 设置游戏库总数
        userWithGamesVO.setGameCount(gameList != null ? gameList.size() : 0);
        
        // 获取总游戏时长
        Integer totalPlayTime = userGameService.getTotalPlayTime(userVO.getId());
        userWithGamesVO.setTotalPlayTime(totalPlayTime != null ? totalPlayTime : 0);
        
        // 获取最近游玩的游戏列表（最多5个）
        List<UserGameVO> recentGames = userGameService.getRecentPlayedGames(userVO.getId(), 5);
        userWithGamesVO.setRecentGames(recentGames);
        
        return userWithGamesVO;
    }
}
